package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Message;
import com.example.demo.util.VerficodeUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Controller
public class VerifyController {
    @Resource
    private  StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/verify")
    public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("image/jpeg");
        VerficodeUtil vc=new VerficodeUtil();
        BufferedImage image = vc.getImage();
        String text = vc.getText();
        if(text!=null&&!"".equals(text)) {
            //HttpSession session = req.getSession();
           // session.setAttribute("index_code", text);
            stringRedisTemplate.opsForValue().set("index_code",text,2, TimeUnit.MINUTES);
            VerficodeUtil.output(image, resp.getOutputStream());
        }else resp.getWriter().write(JSONObject.toJSONString(Message.failure(400, "Code generate is error")));
    }
}
